package test.interceptor;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import test.controller.HelloWorldController;
import test.model.User;

@Component
public class SecurityInterceptor extends HandlerInterceptorAdapter {

	private static Pattern p = Pattern.compile("/\\w+/login/?");

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		User u = (User) request.getSession().getAttribute("user");

		String uri = request.getRequestURI();
		if (p.matcher(uri).find()) {
			return true;
		}
		
		if (u == null) {
			String url = MvcUriComponentsBuilder.fromMethodName(HelloWorldController.class, "login").build().toString();

			System.out.println("Send redirect to " + url);

			response.sendRedirect(url);

			return false;
		}
		return true;
	}

}
